package com.changgou.collect.controller;

import com.changgou.collect.pojo.Collect;
import com.changgou.collect.service.CollectService;
import com.github.pagehelper.PageInfo;
import entity.Result;
import entity.StatusCode;
import entity.TokenDecode;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/****
 * @Author:shenkunlin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/
@RestController
@RequestMapping("/collect")
public class CollectController {

    @Autowired
    private CollectService collectService;
    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 添加收藏和删除收藏
     * CollectStatus:   1=收藏，0=取消收藏
     *
     * @param
     * @return
     */
    @GetMapping("/addCollect/{skuid}/{collectStatus}")
    public Result addCollect(@PathVariable(value = "skuid") String skuid, @PathVariable(value = "collectStatus") String collectStatus) throws Exception {

        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        //判断收藏状态，点击取消收藏， 1=收藏，0=取消收藏
        if (collectStatus.equalsIgnoreCase("1")) {
            collectService.add(skuid, username);
            return new Result(true, StatusCode.OK, "已添加收藏！");
        }

        //取消收藏，则去数据库删除数据
        if (collectStatus.equalsIgnoreCase("0")) {
            boolean delFlag = collectService.deleteCollectByUsernameAndId(username, skuid);
            if (delFlag) {
                return new Result(true, StatusCode.OK, "取消收藏成功");
            } else {
                return new Result(false, StatusCode.ERROR, "取消收藏失败");
            }
        }
        return null;
    }

    /**
     * 查询收藏
     */
    @GetMapping(value = "/search")
    public Result<List<Collect>> findList() {
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        List<Collect> collects = collectService.findList(username);
        return new Result<>(true, StatusCode.OK, "查询成功", collects);
    }

    /**
     * 判断是否收藏
     */
    @RequestMapping("/isCollected/{skuid}")
    public Result isCollected(@PathVariable(value = "skuid") String skuid, HttpServletRequest request) {
        String token = request.getParameter("Authorization");
        if (StringUtils.isEmpty(token)) {
            return new Result(false, StatusCode.ERROR, "未登录");
        }

        String username = tokenDecode.decodeToken(token).get("username");
        boolean flag = collectService.isCollect(skuid, username);
        if (flag) {
            return new Result(true, StatusCode.OK, "已经被收藏", true);
        } else {
            return new Result(true, StatusCode.OK, "未被收藏", false);
        }
    }
}

